<template>
  <div class="farmer-order-container">
    <el-card class="box-card">
      <template #header>
        <div class="card-header">
          <span>订单管理</span>
          <div class="header-actions">
            <el-input
              v-model="searchQuery"
              placeholder="搜索订单号/产品名称"
              style="width: 250px;"
              clearable
              @clear="fetchOrders"
              @keyup.enter="searchOrders"
            >
              <template #append>
                <el-button @click="searchOrders">
                  <el-icon><Search /></el-icon>
                </el-button>
              </template>
            </el-input>
          </div>
        </div>
      </template>
      
      <!-- 订单状态选项卡 -->
      <el-tabs v-model="activeTab" @tab-click="handleTabClick">
        <el-tab-pane label="全部订单" name="all"></el-tab-pane>
        <el-tab-pane label="待确认" name="PENDING"></el-tab-pane>
        <el-tab-pane label="已确认" name="CONFIRMED"></el-tab-pane>
        <el-tab-pane label="已发货" name="SHIPPED"></el-tab-pane>
        <el-tab-pane label="已完成" name="COMPLETED"></el-tab-pane>
        <el-tab-pane label="已取消" name="CANCELLED"></el-tab-pane>
      </el-tabs>
      
      <!-- 订单表格 -->
      <el-table :data="orders" style="width: 100%" v-loading="loading">
        <el-table-column prop="orderNumber" label="订单号" width="180" />
        <el-table-column prop="productName" label="产品名称" />
        <el-table-column prop="quantity" label="数量" width="100">
          <template #default="scope">
            {{ scope.row.quantity }} {{ scope.row.unit }}
          </template>
        </el-table-column>
        <el-table-column prop="totalAmount" label="金额" width="120">
          <template #default="scope">
            ¥{{ scope.row.totalAmount.toFixed(2) }}
          </template>
        </el-table-column>
        <el-table-column prop="customerName" label="客户" width="120" />
        <el-table-column prop="orderDate" label="下单时间" width="180" />
        <el-table-column prop="status" label="状态" width="100">
          <template #default="scope">
            <el-tag :type="getStatusType(scope.row.status)">
              {{ getStatusText(scope.row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="240">
          <template #default="scope">
            <el-button size="small" @click="viewOrder(scope.row)">查看</el-button>
            <el-button 
              size="small" 
              type="primary" 
              v-if="scope.row.status === 'PENDING'"
              @click="confirmOrder(scope.row)"
            >
              确认
            </el-button>
            <el-button 
              size="small" 
              type="success" 
              v-if="scope.row.status === 'CONFIRMED'"
              @click="shipOrder(scope.row)"
            >
              发货
            </el-button>
            <el-button 
              size="small" 
              type="danger" 
              v-if="['PENDING', 'CONFIRMED'].includes(scope.row.status)"
              @click="cancelOrder(scope.row)"
            >
              取消
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      
      <!-- 分页组件 -->
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[10, 20, 30, 50]"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>
    
    <!-- 查看订单详情对话框 -->
    <el-dialog v-model="dialogVisible" title="订单详情" width="800px">
      <div class="order-detail" v-if="selectedOrder">
        <el-descriptions title="基本信息" :column="2" border>
          <el-descriptions-item label="订单号">{{ selectedOrder.orderNumber }}</el-descriptions-item>
          <el-descriptions-item label="下单时间">{{ selectedOrder.orderDate }}</el-descriptions-item>
          <el-descriptions-item label="订单状态">
            <el-tag :type="getStatusType(selectedOrder.status)">
              {{ getStatusText(selectedOrder.status) }}
            </el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="支付方式">{{ selectedOrder.paymentMethod }}</el-descriptions-item>
          <el-descriptions-item label="客户姓名">{{ selectedOrder.customerName }}</el-descriptions-item>
          <el-descriptions-item label="联系电话">{{ selectedOrder.customerPhone }}</el-descriptions-item>
        </el-descriptions>
        
        <el-divider />
        
        <h3>产品信息</h3>
        <el-table :data="[selectedOrder]" style="width: 100%">
          <el-table-column prop="productName" label="产品名称" />
          <el-table-column prop="quantity" label="数量" width="120">
            <template #default="scope">
              {{ scope.row.quantity }} {{ scope.row.unit }}
            </template>
          </el-table-column>
          <el-table-column prop="unitPrice" label="单价" width="120">
            <template #default="scope">
              ¥{{ scope.row.unitPrice.toFixed(2) }}
            </template>
          </el-table-column>
          <el-table-column prop="totalAmount" label="总金额" width="120">
            <template #default="scope">
              ¥{{ scope.row.totalAmount.toFixed(2) }}
            </template>
          </el-table-column>
        </el-table>
        
        <el-divider />
        
        <h3>收货信息</h3>
        <el-descriptions :column="1" border>
          <el-descriptions-item label="收货地址">{{ selectedOrder.shippingAddress }}</el-descriptions-item>
          <el-descriptions-item label="物流公司" v-if="selectedOrder.logisticsCompany">
            {{ selectedOrder.logisticsCompany }}
          </el-descriptions-item>
          <el-descriptions-item label="运单号" v-if="selectedOrder.trackingNumber">
            {{ selectedOrder.trackingNumber }}
          </el-descriptions-item>
          <el-descriptions-item label="发货时间" v-if="selectedOrder.shippingDate">
            {{ selectedOrder.shippingDate }}
          </el-descriptions-item>
        </el-descriptions>
        
        <el-divider />
        
        <h3>备注信息</h3>
        <el-input
          type="textarea"
          v-model="selectedOrder.notes"
          :rows="3"
          readonly
        />
      </div>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">关闭</el-button>
          <el-button 
            type="primary" 
            v-if="selectedOrder && selectedOrder.status === 'PENDING'"
            @click="confirmSelectedOrder"
          >
            确认订单
          </el-button>
          <el-button 
            type="success" 
            v-if="selectedOrder && selectedOrder.status === 'CONFIRMED'"
            @click="showShippingDialog"
          >
            发货
          </el-button>
        </span>
      </template>
    </el-dialog>
    
    <!-- 发货对话框 -->
    <el-dialog v-model="shippingDialogVisible" title="订单发货" width="500px">
      <el-form :model="shippingForm" label-width="120px">
        <el-form-item label="物流公司">
          <el-select v-model="shippingForm.logisticsCompany" placeholder="选择物流公司">
            <el-option label="顺丰速运" value="SF Express" />
            <el-option label="中通快递" value="ZTO Express" />
            <el-option label="圆通速递" value="YTO Express" />
            <el-option label="韵达快递" value="YD Express" />
            <el-option label="申通快递" value="STO Express" />
            <el-option label="京东物流" value="JD Logistics" />
          </el-select>
        </el-form-item>
        <el-form-item label="运单号">
          <el-input v-model="shippingForm.trackingNumber" placeholder="请输入运单号" />
        </el-form-item>
        <el-form-item label="备注">
          <el-input type="textarea" v-model="shippingForm.remarks" :rows="3" />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="shippingDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitShipping">确认发货</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import { ref, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Search } from '@element-plus/icons-vue'
import { orderAPI } from '@/api/api'

export default {
  name: 'FarmerOrderManagement',
  components: {
    Search
  },
  setup() {
    // 数据定义
    const orders = ref([])
    const loading = ref(false)
    const total = ref(0)
    const currentPage = ref(1)
    const pageSize = ref(10)
    const activeTab = ref('all')
    const searchQuery = ref('')
    const dialogVisible = ref(false)
    const shippingDialogVisible = ref(false)
    const selectedOrder = ref(null)
    const shippingForm = ref({
      logisticsCompany: '',
      trackingNumber: '',
      remarks: ''
    })
    
    // 获取订单列表
    const fetchOrders = async () => {
      loading.value = true
      
      try {
        // 构建查询参数
        const params = {
          page: currentPage.value,
          size: pageSize.value,
          search: searchQuery.value || undefined
        }
        
        // 如果选择了特定状态，添加状态过滤
        if (activeTab.value !== 'all') {
          params.status = activeTab.value
        }
        
        // 调用真实API获取订单数据
        const response = await orderAPI.getOrders(params)
        
        if (response.success) {
          orders.value = response.data.list || []
          total.value = response.data.totalItems || 0
        } else {
          ElMessage.error('获取订单列表失败: ' + response.message)
        }
      } catch (error) {
        console.error('获取订单列表失败:', error)
        ElMessage.error('获取订单列表失败: ' + (error.message || '未知错误'))
      } finally {
        loading.value = false
      }
    }
    
    // 搜索订单
    const searchOrders = () => {
      currentPage.value = 1
      fetchOrders()
    }
    
    // 处理选项卡切换
    const handleTabClick = () => {
      currentPage.value = 1
      fetchOrders()
    }
    
    // 获取状态文本
    const getStatusText = (status) => {
      const statusMap = {
        'PENDING': '待确认',
        'CONFIRMED': '已确认',
        'SHIPPED': '已发货',
        'COMPLETED': '已完成',
        'CANCELLED': '已取消'
      }
      return statusMap[status] || status
    }
    
    // 获取状态标签类型
    const getStatusType = (status) => {
      const typeMap = {
        'PENDING': 'warning',
        'CONFIRMED': 'primary',
        'SHIPPED': 'success',
        'COMPLETED': 'success',
        'CANCELLED': 'danger'
      }
      return typeMap[status] || ''
    }
    
    // 查看订单详情
    const viewOrder = async (order) => {
      try {
        // 通过API获取完整的订单详情
        const response = await orderAPI.getOrderById(order.id)
        
        if (response.success) {
          selectedOrder.value = response.data
          dialogVisible.value = true
        } else {
          ElMessage.error('获取订单详情失败: ' + response.message)
        }
      } catch (error) {
        console.error('获取订单详情失败:', error)
        ElMessage.error('获取订单详情失败: ' + (error.message || '未知错误'))
      }
    }
    
    // 确认订单
    const confirmOrder = (order) => {
      ElMessageBox.confirm(
        `确定要确认订单 ${order.orderNumber} 吗？`,
        '确认订单',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'info',
        }
      )
        .then(async () => {
          try {
            // 调用API确认订单
            const response = await orderAPI.updateOrder({
              id: order.id,
              status: 'CONFIRMED'
            })
            
            if (response.success) {
              ElMessage.success('订单确认成功')
              // 更新本地状态
              order.status = 'CONFIRMED'
              // 刷新列表
              fetchOrders()
            } else {
              ElMessage.error('订单确认失败: ' + response.message)
            }
          } catch (error) {
            console.error('订单确认失败:', error)
            ElMessage.error('订单确认失败: ' + (error.message || '未知错误'))
          }
        })
        .catch(() => {
          ElMessage.info('已取消操作')
        })
    }
    
    // 确认选中的订单
    const confirmSelectedOrder = () => {
      if (selectedOrder.value) {
        ElMessageBox.confirm(
          `确定要确认订单 ${selectedOrder.value.orderNumber} 吗？`,
          '确认订单',
          {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'info',
          }
        )
          .then(async () => {
            try {
              // 调用API确认订单
              const response = await orderAPI.updateOrder({
                id: selectedOrder.value.id,
                status: 'CONFIRMED'
              })
              
              if (response.success) {
                ElMessage.success('订单确认成功')
                selectedOrder.value.status = 'CONFIRMED'
                // 刷新列表
                fetchOrders()
              } else {
                ElMessage.error('订单确认失败: ' + response.message)
              }
            } catch (error) {
              console.error('订单确认失败:', error)
              ElMessage.error('订单确认失败: ' + (error.message || '未知错误'))
            }
          })
          .catch(() => {
            ElMessage.info('已取消操作')
          })
      }
    }
    
    // 显示发货对话框
    const showShippingDialog = () => {
      shippingForm.value = {
        logisticsCompany: '',
        trackingNumber: '',
        remarks: ''
      }
      shippingDialogVisible.value = true
    }
    
    // 提交发货
    const submitShipping = async () => {
      if (!shippingForm.value.logisticsCompany || !shippingForm.value.trackingNumber) {
        ElMessage.warning('请填写物流公司和运单号')
        return
      }
      
      try {
        // 调用API发货
        const response = await orderAPI.shipOrder(selectedOrder.value.id, {
          logisticsCompany: shippingForm.value.logisticsCompany,
          trackingNumber: shippingForm.value.trackingNumber,
          remarks: shippingForm.value.remarks
        })
        
        if (response.success) {
          ElMessage.success('订单发货成功')
          shippingDialogVisible.value = false
          
          // 刷新订单详情和列表
          const orderResponse = await orderAPI.getOrderById(selectedOrder.value.id)
          if (orderResponse.success) {
            selectedOrder.value = orderResponse.data
          }
          
          fetchOrders()
        } else {
          ElMessage.error('订单发货失败: ' + response.message)
        }
      } catch (error) {
        console.error('订单发货失败:', error)
        ElMessage.error('订单发货失败: ' + (error.message || '未知错误'))
      }
    }
    
    // 发货订单
    const shipOrder = (order) => {
      selectedOrder.value = order
      showShippingDialog()
    }
    
    // 取消订单
    const cancelOrder = (order) => {
      ElMessageBox.confirm(
        `确定要取消订单 ${order.orderNumber} 吗？`,
        '取消订单',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
        }
      )
        .then(async () => {
          try {
            // 调用API取消订单
            const response = await orderAPI.cancelOrder(order.id)
            
            if (response.success) {
              ElMessage.success('订单已取消')
              // 刷新列表
              fetchOrders()
            } else {
              ElMessage.error('订单取消失败: ' + response.message)
            }
          } catch (error) {
            console.error('订单取消失败:', error)
            ElMessage.error('订单取消失败: ' + (error.message || '未知错误'))
          }
        })
        .catch(() => {
          ElMessage.info('已取消操作')
        })
    }
    
    // 分页相关方法
    const handleSizeChange = (newSize) => {
      pageSize.value = newSize
      fetchOrders()
    }
    
    const handleCurrentChange = (newPage) => {
      currentPage.value = newPage
      fetchOrders()
    }
    
    // 生命周期钩子
    onMounted(() => {
      fetchOrders()
    })
    
    return {
      orders,
      loading,
      total,
      currentPage,
      pageSize,
      activeTab,
      searchQuery,
      dialogVisible,
      shippingDialogVisible,
      selectedOrder,
      shippingForm,
      fetchOrders,
      searchOrders,
      handleTabClick,
      getStatusText,
      getStatusType,
      viewOrder,
      confirmOrder,
      confirmSelectedOrder,
      showShippingDialog,
      submitShipping,
      shipOrder,
      cancelOrder,
      handleSizeChange,
      handleCurrentChange
    }
  }
}
</script>

<style scoped>
.farmer-order-container {
  padding: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: center;
}

.el-divider {
  margin: 24px 0;
}

h3 {
  margin: 0 0 16px 0;
  font-weight: 500;
  color: #333;
}
</style> 